package net.wangds.yunz.auth.handler;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.wangds.auth.module.Account;
import net.wangds.auth.token.cache.TokenCache;
import net.wangds.jwt.comp.JwtTokenComp;
import net.wangds.log.helper.LogHelper;
import net.wangds.spring.utils.SpringUtils;
import net.wangds.utils.IpAddressUtils;
import net.wangds.utils.JsonUtils;
import net.wangds.web.entrypoint.BaseResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 登陆成功处理
 **/
@Component
public class LoginAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    JwtTokenComp mmCmpJwtToken;

    @NoArgsConstructor
    @AllArgsConstructor
    public static class TokenInfo{
        @Getter
        @Setter
        private String token;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) {
        LogHelper.dev("登录成功 on authentication success");
        LogHelper.dev("登录成功："+ JsonUtils.toJsonStr(auth)+","+auth.getPrincipal()+","+auth.getCredentials());
        UserDetails ud = (UserDetails)auth.getPrincipal();
        String token = mmCmpJwtToken.generateAccessToken(ud, IpAddressUtils.getIpAddress(request));
        //response.addHeader("Authorization", "Bearer " + token);
        //response.addHeader("token", "Bearer " + token);
        //保存用户信息到缓存
        TokenCache cache = SpringUtils.getBean(TokenCache.class);
        LogHelper.dev(()->"保存登录session到缓存:"+token+","+JsonUtils.toJsonStr(ud));
        cache.putToken(token, ud);

        if(ud instanceof Account){
            ((Account) ud).setPassword("******");
        }

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try(OutputStream os = response.getOutputStream()){
            os.write(JsonUtils.toJsonStr(BaseResp.of(new TokenInfo(token))).getBytes(StandardCharsets.UTF_8));
            os.flush();
        } catch (IOException e) {
            LogHelper.error(e);
        }

    }
}
